<script>
import env from '../../env.js';
import mapStyle from './custom_map_config.json';
import { debounce } from 'lodash-es';

export default {
  name: 'bmap',
  inheritAttrs: false,
  props: {
    defaultMapCenter: { type: Array, default: () => [] },
    defaultMapStyle: { type: Array, default: undefined },
    disableControl: { type: Boolean, default: false },
    mapContainerStyle: { type: Object, default: undefined },
  },
  data() {
    return {
      id: 'bmap_' + (Number(String(Math.random()).slice(-13)) + Date.now()).toString(36),
      ready: false,
    };
  },
  mounted() {
    const defaultMapCenter = Object.assign([], this.defaultMapCenter);
    this.mapDefaultZoom = 15;
    this.mapDefaultCenter = new BMap.Point(defaultMapCenter[0], defaultMapCenter[1]);
    this.map = new BMap.Map(this.id); // 创建Map实例
    this.map.setMapStyleV2({ styleJson: this.defaultMapStyle || mapStyle });
    //初始化地图,设置中心点坐标和地图级别
    this.map.centerAndZoom(this.mapDefaultCenter, this.mapDefaultZoom);
    this.map.setDisplayOptions({
      poiIcon: false,
      poiText: true,
      indoor: true,
    });
    this.resetMapView = debounce(() => {
      this.map.flyTo(this.mapDefaultCenter, this.mapDefaultZoom);
    }, 100);
    window.addEventListener('resize', this.resetMapView, false);
    // console.log(this.map);
    // this.map.clearLabels();
    this.$watch(
      () => this.disableControl,
      function (disabled) {
        if (disabled) {
          this.map.disableDoubleClickZoom();
          this.map.disableScrollWheelZoom();
          this.map.disableDragging();
          this.map.disableKeyboard();
        } else {
          this.map.enableDoubleClickZoom();
          this.map.enableScrollWheelZoom();
          this.map.enableDragging();
          this.map.enableKeyboard();
        }
      },
      { immediate: true }
    );

    this.ready = true;
    this.$nextTick(() => {
      this.$emit('ready', this.map);
    });
    if (env.DEV) {
      window.map = this.map;
    }
  },
  unmounted() {
    if (env.DEV) {
      window.map = null;
    }
    window.removeEventListener('resize', this.resetMapView, false);
    this.map.destroy();
  },
  render(h) {
    const containerStyle = {
      position: 'absolute',
      top: 0,
      left: 0,
      width: '100%',
      height: '100%',
      zIndex: 0,
    };
    return h(
      'div',
      {
        class: 'map_wrapper',
        style: { position: 'relative', width: '100%', height: '100%' },
      },
      [
        h('div', {
          class: 'map_container',
          style: Object.assign(containerStyle, this.mapContainerStyle),
          attrs: { id: this.id },
        }),
        this.ready ? this.$slots.default && this.$slots.default(this.map) : null,
      ]
    );
  },
};
</script>

<style lang="less">
.map_wrapper {
  .anchorBL,
  .BMap_cpyCtrl.BMap_noprint.anchorBL {
    display: none;
  }
}
</style>
